package top.joylee.example.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.joylee.example.grpc.hello.GreeterGrpc;

import javax.annotation.PostConstruct;

/**
 * stub工厂
 */
@Slf4j
@Component
public class GrpcStub {
    private GreeterGrpc.GreeterBlockingStub blockingStub;

    private GreeterGrpc.GreeterStub stub;

    @Value("${top.joylee.grpc.targetUrl}")
    private volatile String target;

    @PostConstruct
    public void init() {
        if (StringUtils.isEmpty(target)) {
            throw new RuntimeException("初始化gRPC stub 异常,未指定target");
        }
        ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
                .usePlaintext()
                .build();
        this.blockingStub = GreeterGrpc.newBlockingStub(channel);
        this.stub = GreeterGrpc.newStub(channel);
    }

    public GreeterGrpc.GreeterBlockingStub getBlockingStub() {
        return this.blockingStub;
    }

    public GreeterGrpc.GreeterStub getStub() {
        return this.stub;
    }
}
